package com.bos.service.impl;

import com.bos.dao.repositories.AreaRepository;
import com.bos.dao.repositories.FixedAreaRepository;
import com.bos.dao.repositories.OrderRepository;
import com.bos.dao.repositories.WorkBillRepository;
import com.bos.domian.base.*;
import com.bos.domian.constant.Constants;
import com.bos.service.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author misterWei
 * @create 2018年11月23号:20点39分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private FixedAreaRepository fixedAreaRepository;
    @Autowired
    private AreaRepository areaRepository;

  //调用MQ发送短信通知
    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsQueueTemplate;

    @Override
    public void orderAdd(Order order) {
        order.setStatus("1"); //未取件状态
        //3 生成订单号 使用UUID
        order.setOrderTime(new Date());
        order.setOrderNum(UUID.randomUUID().toString().replace("-", ""));
           // 寄件人 省市区
        Area area = order.getSendArea();
        Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(
                area.getProvince(), area.getCity(), area.getDistrict());
        // 收件人 省市区
        Area recArea = order.getSendArea();
        Area persistRecArea = areaRepository
                .findByProvinceAndCityAndDistrict(recArea.getProvince(),
                        recArea.getCity(), recArea.getDistrict());
        order.setSendArea(persistArea);
        order.setRecArea(persistRecArea);
        //1 查询发货人的地址是否与customer的地址匹配 如果匹配就可以自动分单 斌返回一个分区关联的ID
        String fixedAreaId = WebClient.create(Constants.CRM_MANAGERMENT + "/services/customerService/findFixedAreaByAddress?address=" + order.getSendAddress()).get(String.class);

       //根据CRM的完全匹配地址实现自动分单
        if (fixedAreaId != null) {
            //查询出来这个定区的对象,将其区域快递员进行匹配处理
            FixedArea one = fixedAreaRepository.findOne(fixedAreaId);
            if (one != null) {
                order.setOrderType("1");//自动分单
                //2 将这个快递员关联到自动匹配单的功能
                Iterator<Courier> iterator = one.getCouriers().iterator();
                if (iterator.hasNext()) {
                    autoOrderSave(order,iterator.next());
                    //4  给快递员发送短信,准备去拿取快递 还有生成工单数据
                    createWorkBill(order);
                    return;
                }
            }
        }
        //根据关键字进行自动分单   辅助关键字  2个关键字等
        if (persistArea!=null) {
            for (SubArea subArea : persistArea.getSubareas()) {
                //如果包含关键字 查找分区 查出快递员
                if (order.getSendAddress().contains(subArea.getKeyWords())) {
                    Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                    if (iterator.hasNext()) {
                        if (iterator.next()!=null) {
                            autoOrderSave(order,iterator.next());
                            //4  给快递员发送短信,准备去拿取快递 还有生成工单数据
                            createWorkBill(order);
                            return;
                        }
                    }
                }
            }
            for (SubArea subArea : persistArea.getSubareas()) {
                //如果包含辅助关键字 查找分区 查出快递员
                if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
                    Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                    if (iterator.hasNext()) {
                        if (iterator.next()!=null) {
                            autoOrderSave(order,iterator.next());
                            //4  给快递员发送短信,准备去拿取快递 还有生成工单数据
                            createWorkBill(order);
                            return;
                        }

                    }
                }
            }




        }

        //人工分单
        order.setOrderType("2");
        orderRepository.save(order);

    }

    @Override
    public Order findByOrderNum(String orderNum) {
        return orderRepository.findByOrderNum(orderNum);
    }

    @Autowired
    private WorkBillRepository workBillRepository;
    //生成工单发送短信抽取方法
    public void createWorkBill(Order order){
        String randomCode = RandomStringUtils.randomNumeric(4);
        WorkBill workBill = new WorkBill();
        workBill.setType("新");

        workBill.setBuildtime(new Date());
        workBill.setAttachbilltimes(0);
        workBill.setRemark(order.getRemark());
        workBill.setSmsNumber(randomCode);
        workBill.setCourier(order.getCourier());
        workBill.setOrder(order);
        workBill.setPickstate("已通知");
        jmsQueueTemplate.send("bos_sms_queue", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setObject("telephone",order.getCourier().getTelephone());
                mapMessage.setObject("content",randomCode);
                return mapMessage;
            }
        });
        workBillRepository.save(workBill);
    }
    //自动分单保存
    private void autoOrderSave(Order order ,Courier courier){
        order.setOrderType("1");
        order.setCourier(courier);
        orderRepository.save(order);
    }
}
